package com.lw.leetcode.arr.b;

/**
 * Created with IntelliJ IDEA.
 * 1493. 删掉一个元素以后全为 1 的最长子数组
 *
 * @author liw
 * @version 1.0
 * @date 2021/11/10 9:26
 */
public class LongestSubarray {

    public static void main(String[] args) {
        LongestSubarray test = new LongestSubarray();

        int[] arr = {0,1,1,1,0,1,1,0,1,1};
//        int[] arr = {0, 1, 1, 1};
//        int[] arr = {1, 1, 1};
//        int[] arr = {1, 1, 1, 0};
        int i = test.longestSubarray(arr);

        System.out.println(i);
    }


    public int longestSubarray(int[] nums) {
        int last = 0;
        int count = 0;
        int max = 0;
        int z = 0;
        for (int num : nums) {
            if (num == 0) {
                max = Math.max(max, last + count);
                last = count;
                count = 0;
                z++;
            } else {
                count++;
            }
        }
        max = Math.max(max, last + count);
        if (z == 0) {
            return max - 1;
        }
        return max;
    }


    public int longestSubarray2(int[] nums) {
        int last = 0;
        int count = 0;
        int max = 0;
        int zCount1 = 0;
        int zCount2 = 0;

        for (int num : nums) {
            if (num == 0) {

                zCount1++;
                if (zCount1 == 1) {
                   if (zCount2 <= 1) {
                        max = Math.max(max, count + last);
                    } else {
                        max = Math.max(max, count);
                    }
                    last = count;
                    count = 0;
                }
            } else {
                count++;
                if (zCount1 > 0) {
                    zCount2 = zCount1;
                    zCount1 = 0;
                }
            }
        }

        if (zCount2 == 0) {
            max = Math.max(max, count - 1);
        } else if (zCount2 == 1) {
            max = Math.max(max, count + last);
        } else {
            max = Math.max(max, count);
        }

        return max;
    }
}
